﻿using Microsoft.Extensions.Logging;
using Simple.Framework;
using Simple.Framework.Ioc;
using Simple.Framework.Logger;
using Simple.Tools;
using SimpleNet.Net;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Design;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

/*********************************************************
 * 命名空间 Simple.BasicNet.Core.Net
 * 接口名称 MessageHandle
 * 开发人员：11920
 * 创建时间：2023/4/6 16:29:04
 * 描述说明：继承接口然后自定义解析规则，默认解析规则
 * 更改历史：
 * 
 * *******************************************************/
namespace SimpleNet.Handle
{
    public class MessageHandle : IMessageHandle
    {
		protected IContainer container;

	    List<HandleLabel> handleLabels;
        protected ILogger<MessageHandle> logger;
        public MessageHandle(IContainer container)
        {
            this.container = container;
            handleLabels = container.GetService<List<HandleLabel>>();
            logger = container.GetService<ILogger<MessageHandle>>();
            container.Register<IDataPack, DataPack>();
			Initalization();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public virtual void AnalysisHandle(BlockingCollection<IDataPack> qdataPacks,byte[] data,int length)
        {
			IDataPack dataPack = this.container.GetService<IDataPack>();
			dataPack.ReceiveBuffer = new byte[length];
			Array.Copy(data, 0, dataPack.ReceiveBuffer, 0, length);
			SetDataPack(dataPack);
			qdataPacks.Add(dataPack);
		}

        /// <summary>
        /// 后续逻辑处理
        /// </summary>
        /// <param name="context"></param>
        public virtual void Handle(IContext context)
        {
            if (ToolSimpleCheck.IsNull(handleLabels))
            {
				handleLabels = container.GetService<List<HandleLabel>>();
			}
            if (handleLabels.Where(label => label.IsRange(context.CurrentPack.CommandID)).Any())
            {
                var label = handleLabels.FirstOrDefault(label => label.IsRange(context.CurrentPack.CommandID));
                var handle = container.GetService(label.HandType);

                ((BaseHandle)handle).SetContext(context);
				
				foreach (var method in label.HandType.GetMethods().Where(m => m.IsDefined(typeof(MessageNumberAttribute))))
                {
                    MessageNumberAttribute NumberAttr = method.GetCustomAttribute<MessageNumberAttribute>();

                    if (NumberAttr.Number == context.CurrentPack.CommandID)
                    {
							method.Invoke(handle, new object[] { });
					}
                }
            }
            else
            {
				logger.LogError($"1.解析消息编号调用相关处理方法!");
				logger.LogError($"2.请检查是否配置相关业务方法!");
				logger.LogError($"3.请重写Messagehandle,写出如何解析出消息编号!");
				logger.LogError($"4.消息号{context.CurrentPack.CommandID}不存在处理的方法,请检查!");
            }
        }

        public virtual void Handled(IContext context)
        {

        }

        public void Initalization()
        {
        }

        public virtual void SetDataPack(IDataPack dataPack)
        {
			
		}

	}
}
